<template>
  <el-dialog 
    class="edit-dialog"
    :visible.sync="isVisible"
    :close-on-click-modal="false"
    :title="title"
    :fullscreen="true">
    <div class="filter-container">
      <div class="filter-row">
        <div class="filter-item">
          <span class="filter-title">场所名称：</span>
          <el-input placeholder="请输入场所名称" size="small"
                class="date-range-item" v-model="searchObj.csName"/>
        </div>
        <div class="filter-item">
          <span class="filter-title">机构名称：</span>
          <el-input size="small" placeholder="所属机构名称"
                class="search-item" v-model="searchObj.orgName"/>
        </div>
        <div class="filter-item">
          <span class="filter-title">信用代码：</span>
          <el-input size="small" placeholder="统一社会信用代码"
                    class="search-item" v-model="searchObj.unifiedCode"/>
        </div>
      </div>
      <div class="filter-row">
        <div class="filter-item">
          <span class="filter-title">所属区域：</span>
          <el-cascader
            v-if="isVisible"
            class="date-range-item"
            size="small"
            :props="props"
            @change="handleChange"
            v-model="searchObj.areaIds"
          ></el-cascader>
        </div>
        <div class="filter-item">
          <span class="filter-title">申领时间：</span>
           <el-date-picker
            size="small"
            class="search-item date-range-item"
            v-model="searchObj.timeRange"
            type="datetimerange"
            format="yyyy-MM-dd  HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :range-separator="null"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </div>
        <div class="filter-item">
          <el-button size="small" @click="search" class="filter-item" type="primary">
            查询
          </el-button>
          <el-button size="small" @click="reset" class="filter-item">
            重置
          </el-button>
        </div>
      </div>
    </div>
    <el-table
      size="medium"
      :data="tabItems"
      ref="table"
      style="width: 100%;"
      empty-text="请点击查询按钮查询数据"
      v-loading="tabLoading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column label="场所码编号" align="center"
        prop="id"
      />
      <el-table-column label="场所名称" align="left"
        prop="csName"
      />
      <el-table-column label="场所类型" align="left"
        prop="typeSecond"
      />
      <el-table-column label="机构名称" align="left"
        prop="orgName"
        min-width="80px"
      />
      <el-table-column label="场所地址" align="center"
        prop="fullAddress"
        min-width="100px"
      />
      <el-table-column label="联系人手机号" align="center"
        prop="applicantPhone"
      />
      <el-table-column label="申领时间" align="center"
        prop="createTime"
        min-width="120px"
      />
    </el-table>
    <div class="pagination-box">
      <el-pagination
        :background="true"
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-count="pagination.pageCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button size="medium" @click="isVisible=false">取 消</el-button>
      <el-button size="medium" type="primary" :loading="submitLoading" @click="editSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import areaConvert from '@/utils/areaCodeCov.js';
import {insertAdminCs, selectCsInfoPage, commAreaUrl, commUserAreaUrl} from '@/http/apiUrls.js';
export default {
  name: 'SetCSMForm',
  props: {
    // 弹窗显示
    dialogVisible: { type: Boolean, default: false}
  },
  computed: {
    // 控制显示
    isVisible: {
      get() { 
        return this.dialogVisible; 
      },
      set() {
        this.$emit('close')
        this.tabItems = [];
        this.csSelection = []
      }
    },
    // 标题
    title:{
      get(){
        return '管理员添加场所码'
      }
    }
  },
  data() {
    return {
      adminId: '',
      adminAreaCode: null,
      submitLoading:false,
      tabLoading: false,
      tableKey: 0,
      pageItems: 10, // 每页查询条数
      pagination: {
        currentPage: 1, // 当前页
        pageSize: 10, // 每页显示条数
        pageCount: 1, // 总页数
      },
      tabItems: [],
      csSelection: [],
      searchObj: this.initSearchObj(),
      props: {
        lazy: true,
        checkStrictly: true,
        lazyLoad: (node, resolve) => {
          const { level } = node;
          const nodes = [];          
          let type = level == 0 ? this.adminAreaCode : node.value;
          this.provinceFn(type)
            .then((res) => {
              // 节点数组
              res.map((item) => {
                let obj = {
                  value: item.code,
                  label: item.fullName,
                  leaf: item.level >= 4
                };
                nodes.push(obj);
              });
              // resolve 节点返回
              resolve(nodes);
            })
            .catch((error) => {
              console.log(error);
            });
        }
      },
    }
  },
  methods: {
    handleSelectionChange(val) {
      this.csSelection = val;
    },
    // 修改传递值
    setEditObj(val) {
      if(val){
        console.log('val',val);
        this.adminId = val.id
        this.adminAreaCode = val.areaCode
      }
    },
    initSearchObj(){
      return {
        unifiedCode: '',
        csName: '',
        orgName: '',
        timeRange: [],
        areaIds: []
      }
    },
    getSearchObj(){
      let obj = {...this.searchObj};
      const ids = obj.areaIds;
      let areaCode = '';
      if(ids && ids.length > 0){
        areaCode = ids[ids.length-1]
        let likeVal = areaConvert(areaCode);
        obj.areaCode = likeVal
      }else{
        let likeVal = this.adminAreaCode;
        likeVal = areaConvert(likeVal);
        obj.areaCode = likeVal
      }
      return obj;
    },
    getExtraObj(){
      let obj = this.searchObj;
      let extra = {};
      if(obj.timeRange && obj.timeRange.length == 2 ){
        extra.createTime_ge = obj.timeRange[0]
        extra.createTime_le = obj.timeRange[1]
      }
      return extra
    },
    getArea(code){
      return new Promise((resolve, reject) => {
        const requestData = {
          parentCode: code
        }
        if(code){
          this.$postJson(commAreaUrl, requestData).then(res => {
            if(res){
              resolve(res)
            }else{
              resolve([])
            }
          })
        }else{
          this.$postJson(commUserAreaUrl, {}).then(res => {
            if(res){
              resolve(res)
            }else{
              resolve([])
            }
          })
        }
      })
    },
    // 获取省市区街道
    provinceFn(code) {
      // 此处是一个promise 直接返回
      return this.getArea(code);
    },
    // 监听数据变化
    handleChange(value) {
      console.log(value);
    },
    search(){
      this.getData(1, this.pageItems, this.getSearchObj(), this.getExtraObj())
    },
    reset(){
      this.searchObj = this.initSearchObj()
      this.getData(1, this.pageItems, {}, {})
    },
    getData(current , size, model, extra){
      let requestData = {
        current,
        size,
        model,
        extra
      }
      this.tabLoading = true;
      this.$postJson(selectCsInfoPage, requestData).then(res => {
        this.tabLoading = false;
        if(res){
          const pagination = {
            currentPage: parseInt(res.current), // 当前页面号
            pageSize: parseInt(res.size), // 每页条目数
            pageCount: parseInt(res.pages), // 总页面数
          }
          this.pagination = pagination;
          this.tabItems = res.records;
        }
      })
    },
    async handleCurrentChange(val) {
      await this.getData(val, this.pageItems, this.getSearchObj(), this.getExtraObj())
    },
    async handleSizeChange(val) {
      this.pageItems = val
      await this.getData(1, this.pageItems, this.getSearchObj(), this.getExtraObj())
    },
    itemDetail(item){
      this.$router.push({
        path: "/csm/csmManageDetail",
        query: {id: item.id}
      })
    },
    editSubmit(){
      if(this.csSelection && this.csSelection.length > 0){
        const csIds = this.csSelection.map(m => m.csId)
        const requestData = {
          adminId: this.adminId,
          csIds
        }
        this.submitLoading = true;
        this.$postJson(insertAdminCs, requestData).then(res => {
          this.submitLoading = false;
          if(res){
            this.$message({
              type: 'success',
              message: '场所添加成功!'
            });
            this.isVisible = false;
            this.$emit('success')
          }
        })
      }else{
        console.log(this.adminId);
        this.$message({
          type: 'error',
          message: '请至少选择一个场所码!'
        });
      }
      console.log(this.csSelection);
    },
  }
}
</script>
<style lang="scss">
.edit-dialog{
  .el-dialog__header{
    padding: 15px 20px 15px;
    .el-dialog__title{
      color: #fff;
    }

    i{
      color: #fff;
    }
    
    background-color: #006ACC;
  }

  .el-dialog__footer{
    padding: 15px 20px 15px;
    border-top: 1px solid #dfe4ea;
  }
}
</style>
<style lang="scss" scoped>
.filter-row {
  width: 100%;
  margin-bottom: 8px;
  display: flex;
  .filter-item {
    width: fit-content;
    .filter-title {
      display:inline-block;
      width:100px;
      text-align:right;
      margin-left: 4px;
    }
  }
}
</style>